/**
 * 准备函数
 */
var operateRight = new Object();
var CompanyStatus = {
	'DISABLE' : 0 // 禁用
	,'ENABLE' : 1 // 启用、正式
	,'TEST' : 2		// 试用
	,'INVALID' : 3  // 过期、失效
};
$(document).ready(function() {
	// 加载权限
	loadRight();

	// 加载表格
	queryCompany();
	
	var defDate = getAfterDate(7);
	// 加载form模块
	layui.use(['form','laydate'], function() {
		$form = layui.form;
		$layer = layui.laydate;
		
		// 日期范围
		$layer.render({
			elem : '#cValidUntilDate',
			format : Global.DATE_FORMAT_STR,
			value : defDate,
			trigger: 'click',
			min : getCurrentDate()
		});
		
		// 日期范围
		$layer.render({
			elem : '#mValidUntilDate',
			format : Global.DATE_FORMAT_STR,
			value : defDate,
			trigger: 'click',
			min : getCurrentDate()
		});
		
		$form.on('radio(cStatusFilter)', function(data) {
			if(data.value == CompanyStatus.TEST){
				$(".cValidUntilDateTd").show();
			}else{
				$(".cValidUntilDateTd").hide();
			}
		});
		
		$form.on('radio(mStatusFilter)', function(data) {
			if(data.value == CompanyStatus.TEST){
				$(".mValidUntilDateTd").show();
			}else{
				$(".mValidUntilDateTd").hide();
			}
		});
		
		// 代理商创建
		$form.on('select(cAgentId)', function(data) {
			if(Utils.isNotNull(data.value)){
				$(".isLoginTd").show();
			}else{
				$(".isLoginTd").hide();
			}
		});
		
		// 代理商修改
		$form.on('select(mAgentId)', function(data) {
			if(Utils.isNotNull(data.value)){
				$(".isLoginTd").show();
			}else{
				$(".isLoginTd").hide();
			}
		});
		
		// 版本创建
		$form.on('select(cVersionId)', function(data) {
			var $opt = $(data.elem).find("option:checked");
			setLimitData(false, data.value, $opt);
		});
		
		// 版本修改
		$form.on('select(mVersionId)', function(data) {
			var $opt = $(data.elem).find("option:checked");
			setLimitData(true, data.value, $opt);
		});
	});

	// 绑定函数
	$("#queryButton").bind("click", confirmQueryCompany);
	$("#createButton").bind("click", showCreateCompanyDialog);
	$("#confirmCreateButton").bind("click", confirmCreateCompany);
	$("#confirmModifyButton").bind("click", confirmModifyCompany);
	$("#confirmSetCompanyLogoButton").bind("click", confirmSetCompanyLogo);
	$("#confirmResetPassword").bind("click", resetPassword);
	$("#saveButtonPlayConfig").bind("click", setPlayerGlobalOption);
	$("#confirmRechargeButton").bind("click", confirmRechargeCompany);
	$("#confirmModifyCompanyStatusButton").bind("click", confirmModifyCompanyStatus);
	
});

/**
 * 设置数据
 * 
 * @param isEdit
 * @param dataV
 * @param $opt
 */
function setLimitData(isEdit, dataV, $opt){
	var $userLimit = $('#cUserLimit');
	var $materiallimit = $('#cMaterialTotalLimit');
	if(isEdit){
		$userLimit = $('#mUserLimit');
		$materiallimit = $('#mMaterialTotalLimit');
	}
	
	if (Utils.isNotNull(dataV)) {
		$userLimit.val($opt.attr('userLimit'));
		$materiallimit.val(Utils.toFormatDecimal(getFileSizeMByB($opt.attr('materiallimit')),0));
	}else{
		$userLimit.val('');
		$materiallimit.val('');
	}
}

/**
 * 加载权限
 */
function loadRight() {
	operateRight.oemCofing = $("#oemCofing").val();
	operateRight.thirdLogin = $("#thirdLogin").val();
	operateRight.modifyUserPwd = $("#modifyUserPwd").val();
	operateRight.modifyRight = $("#modify").val();
	operateRight.deleteRight = $("#delete").val();
	operateRight.playCofingRight = $("#playCofingRight").val();
}

/**
 * 查询
 */
function queryCompany(pageIndex, pageSize) {
	// 组装参数
	var data = {};
	var name = $.trim($("#name").val());
	if (name != "") {
		data['name'] = name;
	}
	var phone = $.trim($("#phone").val());
	if (phone != "") {
		data['phone'] = phone;
	}
	var status = $.trim($("#status").val());
	if (status != "") {
		data['status'] = status;
	}
	var versionId = $.trim($("#versionId").val());
	if (versionId != "") {
		data['versionId'] = versionId;
	}
	var sourceType = $.trim($("#sourceType").val());
	if (sourceType != "") {
		data['sourceType'] = sourceType;
	}
	var agentId = $.trim($("#agentId").val());
	if (agentId != "") {
		data['agentId'] = agentId;
	}

	// 设置分页参数
	setPageIndex(data, pageIndex, pageSize);

	// 调用接口
	var response = callInterface("post", "saas/company/queryCompany", data, false);
	if (response.code == 0) {
		// 清空表格及分页
		$("#companyTable tr:not(:first)").remove();
		$("#pageDiv").html("");

		var count = response.data.totalCount;
		if (count == null || count == 0) {
			var cols = $("#companyTable").find("tr:first th");
			$('#companyTable').append("<tr><td colspan='" + cols.length + "'>无数据!</td></tr>");
			return false;
		}
		var list = response.data.list;
		if (list != null && list.length > 0) {
			for ( var i in list) {
				var trHtml = "<tr>";
				trHtml += "<td align='center'><a href='javascript:showCompanyDetail(" + list[i].id + ");'>" + list[i].name + "</a></td>";
				if(Utils.isNotNull(list[i].agentId)){
					trHtml += "<td align='center'><a href='javascript:showAgentDetail(" + list[i].agentId + ");'>" + list[i].agentName + "</a></td>";
				}else{
					trHtml += "<td align='center'>--</td>";
				}
				trHtml += "<td align='center'>" + Utils.convertNull(ComSourceType[list[i].sourceType]) + "</td>";
				trHtml += "<td align='center'>" + list[i].versionName + "</td>";
				trHtml += "<td align='center'>" + list[i].contacts + "</td>";
				trHtml += "<td align='center'>" + list[i].telephone + "</td>";
				/*trHtml += "<td align='center'>" + Utils.toFormatDecimal(list[i].balance,2) + "</td>";
				trHtml += "<td align='center'>" + list[i].userLimit + "</td>";*/
				trHtml += "<td align='center'>" + Utils.convertNull(list[i].statusName) + "</td>";
				trHtml += "<td align='center'>" + (list[i].status==CompanyStatus.TEST?list[i].validUntilDate:'--') + "</td>";
				trHtml += "<td align='center'>" + Utils.convertNull(list[i].createdTime) + "</td>";
				trHtml += '<td align="center"><a href="javascript:toViewTradeRecord(' + list[i].id + ',\''+list[i].name+'\');">查看</a></td>'
				trHtml += "<td align='center' style='width:350px;' class='operationColumn'>";
				if(operateRight.modifyRight == 1) {
					trHtml += '<a class="edit" href="javascript:showModifyCompanyDialog(' + list[i].id + ');">编辑</a>&nbsp;&nbsp;';
				}
				if(operateRight.oemCofing == 1) {
					trHtml += '<a class="copy" href="javascript:showOemDialog('+list[i].id +',\''+list[i].name+'\');">OEM配置</a>&nbsp;&nbsp;';
				}
				if (operateRight.modifyUserPwd == 1) {
					trHtml += '<a href="javascript:void(0);" class="add" onclick="showResetPasswordDialog(\''
						+ list[i].id + '\' , \'' + list[i].name + '\');">重置密码</a>&nbsp;&nbsp;';
				}
				if (operateRight.thirdLogin == 1) {
					trHtml += "<a href='javascript:void(0);' class='edit' onclick='toThirdLogin(" + list[i].id + ");'>登录</a>&nbsp;&nbsp;";
				}
				if(operateRight.playCofingRight == 1) {
					trHtml += '<a class="copy" href="javascript:showPlayConfigDialog(' + list[i].id + ');">设备配置</a>&nbsp;&nbsp;';
				}
				//if(operateRight.deleteRight == 1) {
				trHtml += "<a href='javascript:void(0);' class='edit' onclick='modifyCompanyStatus(" + JSON.stringify(list[i]) + ");'>账户类型</a>&nbsp;&nbsp;";
				//}
				trHtml += '<a class="copy" href="javascript:showRechargeCompanyDialog(' + list[i].id + ',\''+list[i].name+'\');">充值</a>';
				trHtml += "</td>";
				trHtml += "</tr>";

				// 动态添加一行
				$('#companyTable').append(trHtml);
			}
		}

		// 调用分页
		layui.use(['laypage'], function() {
			var laypage = layui.laypage;
			laypage.render({
				elem : 'pageDiv',
				// pages : pages,
				curr : pageIndex || 1, // 当前页
				count : count,
				limit : pageSize,
				skip : true, // 是否开启跳页
				layout : ['count', 'prev', 'page', 'next', 'limit', 'skip'],
				groups : 5, // 连续显示分页数
				jump : function(obj, first) {
					if (!first) {
						queryCompany(obj.curr, obj.limit);
					}
				}
			});
		});
	}else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 确认查询
 */
function confirmQueryCompany() {
	queryCompany();
}

/**
 * 显示OEM设置
 * 
 * @param id
 * @param name
 */
function showOemDialog(id, name){
	// 显示对话框
	$("#setCompanyLogoDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#setCompanyLogoForm')[0].reset();
	$('#mId').val(id);
	$('#sCompanyName').html(name);
	
	// 调用接口
	var response = callInterface("post", "saas/company/getCompanyOEM", {
		"id" : id
	}, false);
	if (response.code == 0) {
		var data = response.data;
		if (data != null) {
			$("#mDomainName").val(data.domain);
			$("#mWebsiteTitle").val(data.websiteTitle);
			if( Utils.isNotNull(data.logo) ){
				// 初始化预览数据
				getImgPreHtml("mLogo", fuIndex++, "mLogoDiv", true, null, data.logo);
				$("#mLogo").attr("data-url",data.logo);
			}else{
				// 初始化文件选择相关
				$("#mLogo").attr("data-url","");
				var objIB = document.getElementById('mLogo'); 
				objIB.outerHTML = objIB.outerHTML;
				$("#mLogoDiv").html("");
			}
		}
	}
}

/**
 * 确认设置logo和域名
 */
function confirmSetCompanyLogo(){
	// 获取参数
	var data = {};
	data['companyId'] = $('#mId').val();
	
	var domainName = $.trim($('#mDomainName').val());
	if (Utils.isNull(domainName)) {
		showAlert("平台域名不能为空!");
		return false;
	}
	data['domain'] = domainName;
	var title = $.trim($('#mWebsiteTitle').val());
	if (Utils.isNull(title)) {
		showAlert("平台名称不能为空!");
		return false;
	}
	data['websiteTitle'] = title;
	var logo = $("#mLogo").attr("data-url");
	if(Utils.isNull(logo)){
		showAlert("请上传平台Logo!");
		return false;
	}
	data['logo'] = logo;
	
	// 调用接口
	var response = callInterface("post", "saas/company/createOEM", data,
			false);
	if (response.code == 0) {
		showMsg('操作成功!');
		
		// 关闭对话框
		$('#setCompanyLogoDialog').modal("hide");
	} else {
		showErrorMsg(response.code, response.message);
	}
	return false;
}

/**
 * 显示创建对话框
 */
function showCreateCompanyDialog() {
	$("#createCompanyDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#addCompanyForm')[0].reset();

	$("#cAgentId").val("");
	$(".isLoginTd").hide();
	$("#cIsLogin").prop('checked', false);
	$("#cRequirePlan").prop('checked', false);
	$("#cIsWatermark").prop('checked', false);
	$("#cValidUntilDate").val(getAfterDate(7));
	$("#cStatus" + CompanyStatus.TEST).prop('checked', true);
	$(".cValidUntilDateTd").show();
	updateLayuiForm();
}

/**
 * 确认创建
 */
function confirmCreateCompany() {
	// 获取参数
	var data = {};
	var name = $.trim($('#cName').val());
	if (Utils.isNull(name)) {
		showAlert('公司名称不能为空!');
		return false;
	}
	data['name'] = name;
	
	var contacts = $.trim($('#cContacts').val());
	if (Utils.isNull(contacts)) {
		showAlert("联系人不能为空!");
		return false;
	}
	data['contacts'] = contacts;
	
	var telephone = $.trim($('#cTelephone').val());
	if (Utils.isNull(telephone)) {
		showAlert("手机号不能为空!");
		return false;
	}else if (telephone.length != 11) {
		showAlert("手机号格式不正确，请检查!");
		return false;
	}
	data['telephone'] = telephone;
	
	var email = $.trim($('#cEmail').val());
	if (Utils.isNotNull(email)) {
		if (!Utils.validateMail(email)) {
			showAlert("邮箱格式不正确，请检查!");
			return false;
		}
		data['email'] = email;
	}
	
	var address = $.trim($('#cAddress').val());
	if (Utils.isNotNull(address)) {
		data['address'] = address;
	}
	
	var userName = $.trim($('#cUserName').val());
	if (Utils.isNull(userName)) {
		showAlert("用户名不能为空!");
		return false;
	}
	data['userName'] = userName;
	
	var agentId = $.trim($('#cAgentId').val());
	if (Utils.isNotNull(agentId)) {
		var isLogin = $('#cIsLogin').is(":checked");
		data['isLogin'] = isLogin;
		data['agentId'] = agentId;
	}
	
	var status = $("input[name='cStatus']:checked").val();
	if(Utils.isNull(status)){
		showAlert("请选择账户类型!");
		return false;
	}
	data['status'] = status;

	if (status == CompanyStatus.TEST) {
		var validUntilDate = $("#cValidUntilDate").val();
		if (Utils.isNull(validUntilDate)) {
			showAlert("请选择有效期!");
			return false;
		}
		data['validUntilDate'] = validUntilDate;

		// 是否加水印
		var isWatermark = $('#cIsWatermark').is(":checked");
		data['isWatermark'] = isWatermark;
	}
	else {
		data['isWatermark'] = false;
	}
	
	var versionId = $.trim($('#cVersionId').val());
	if (Utils.isNull(versionId)) {
		showAlert("版本不能为空!");
		return false;
	}
	data['versionId'] = versionId;
	
	var userLimit = $.trim($('#cUserLimit').val());
	if (Utils.isNull(userLimit)) {
		showAlert("授权用户数不能为空!");
		return false;
	}
	data['userLimit'] = userLimit;
	
	var materialTotalLimit = $.trim($('#cMaterialTotalLimit').val());
	if (Utils.isNull(materialTotalLimit)) {
		showAlert("素材总空间不能为空!");
		return false;
	}else{
		if (materialTotalLimit <= 0) {
			showAlert("素材总空间必须大于零!");
			return false;
		}
	}
	data['materialSize'] = materialTotalLimit;
	
	//var requirePlanAudit = $('#cRequirePlanAudit').is(":checked");
	data['requirePlanAudit'] = true;
	
	var requirePlan = $('#cRequirePlan').is(":checked");
	data['isAdPaln'] = requirePlan;
	
	// 调用接口
	var response = callInterface("post", "saas/company/createCompany", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');

		// 关闭对话框
		$('#createCompanyDialog').modal("hide");

		// 刷新
		queryCompany();
	}
	else {
		showErrorMsg(response.code, response.message);
	}

	return false;
}

/**
 * 显示删除对话框
 */
function deleteCompany($id) {
	// 设置参数
	var $data = {
		"id" : $id
	};
	// 询问框
	layer.confirm('删除公司将不可恢复，确定删除吗？', {
		offset :'20px',btn: ['确定','取消']
	// 按钮
	}, function() {
		// 调用接口
		var response = callInterface("post", "saas/company/deleteCompany", $data, false);
		if (response.code == 0) {
			showMsg('操作成功!');

			// 刷新
			queryCompany();
		}
		else {
			showErrorMsg(response.code, response.message);
		}
	}, function() {
		return;
	});
}

/**
 * 显示修改对话框
 */
function showModifyCompanyDialog($id) {
	// 显示对话框
	$("#modifyCompanyDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#modifyCompanyForm')[0].reset();
	$("#mId").val($id);
	// 获取详情
	getCompanyDetail($id);
}

/**
 * 确认修改
 */
function confirmModifyCompany() {
	// 获取参数
	var data = {};
	data['id'] = $.trim($("#mId").val());
	var name = $.trim($('#mName').val());
	if (Utils.isNull(name)) {
		showAlert('公司名称不能为空!');
		return false;
	}
	data['name'] = name;
	
	var contacts = $.trim($('#mContacts').val());
	if (Utils.isNull(contacts)) {
		showAlert("联系人不能为空!");
		return false;
	}
	data['contacts'] = contacts;
	
	var telephone = $.trim($('#mTelephone').val());
	if (Utils.isNull(telephone)) {
		showAlert("手机号不能为空!");
		return false;
	}else if (telephone.length != 11) {
		showAlert("手机号格式不正确，请检查!");
		return false;
	}
	data['telephone'] = telephone;
	
	var email = $.trim($('#mEmail').val());
	if (Utils.isNotNull(email)) {
		if (!Utils.validateMail(email)) {
			showAlert("邮箱格式不正确，请检查!");
			return false;
		}
	}
	data['email'] = email;
	
	var address = $.trim($('#mAddress').val());
	data['address'] = address;
	
	var agentId = $.trim($('#mAgentId').val());
	if (Utils.isNotNull(agentId)) {
		var isLogin = $('#mIsLogin').is(":checked");
		data['isLogin'] = isLogin;
		data['agentId'] = agentId;
	}
	
	var versionId = $.trim($('#mVersionId').val());
	if (Utils.isNull(versionId)) {
		showAlert("版本不能为空!");
		return false;
	}
	data['versionId'] = versionId;
	
	var userLimit = $.trim($('#mUserLimit').val());
	if (Utils.isNull(userLimit)) {
		showAlert("授权用户数不能为空!");
		return false;
	}
	data['userLimit'] = userLimit;
	
	var materialTotalLimit = $.trim($('#mMaterialTotalLimit').val());
	if (Utils.isNull(materialTotalLimit)) {
		showAlert("素材总空间不能为空!");
		return false;
	}else{
		if (materialTotalLimit <= 0) {
			showAlert("素材总空间必须大于零!");
			return false;
		}
	}
	data['materialSize'] = materialTotalLimit;
	
	//var requirePlanAudit = $('#mRequirePlanAudit').is(":checked");
	data['requirePlanAudit'] = true;
	
	var requirePlan = $('#mRequirePlan').is(":checked");
	data['isAdPaln'] = requirePlan;

	// 调用接口
	var response = callInterface("post", "saas/company/modifyCompany", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');

		// 关闭对话框
		$('#modifyCompanyDialog').modal("hide");

		// 刷新
		queryCompany(currPage);
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 获取详情
 */
function getCompanyDetail($id) {
	// 调用接口
	var response = callInterface("post", "saas/company/getCompanyDetail", {
		'id' : $id
	}, false);
	if (response.code == 0) {
		var data = response.data;
		if (data != null) {
			$("#mId").val(data.id);
			$("#mName").val(data.name);
			$("#mContacts").val(data.contacts);
			$("#mTelephone").val(data.telephone);
			$("#mEmail").val(data.email);
			$("#mAddress").val(data.address);
			$("#mVersionId").val(data.versionId);
			$("#mValidUntilDate").val(data.validUntilDate);
			$("#mPositionLimit").val(data.positionLimit);
			$("#mMaterialTotalLimit").val(Utils.toFormatDecimal(getFileSizeMByB(data.materialLimit),0));
			$("#mUserLimit").val(data.userLimit);
			
			/*// 是否测试
			if(data.isTest){
				$("#mValidUntilDate").val(data.validUntilDate);
				$(".validUntilDateTd").show();
			}else{
				$(".validUntilDateTd").hide();
			}
			$("#mIsTest").prop('checked',data.isTest);*/
			$("#mUserName").val(data.userName);
			$("#mAgentId").val(data.agentId);
			if (Utils.isNotNull(data.agentId)) {
				$(".isLoginTd").show();
				$("#mIsLogin").prop('checked',data.isLogin);
			}else{
				$(".isLoginTd").hide();
				$("#mIsLogin").prop('checked',false);
			}
			$("#mRequirePlan").prop("checked",data.isAdPlan);
			updateLayuiForm();
		}
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

function confirmModifyCompanyStatus() {
	var data = {};
	var companyId = $("#companyId").val();
	data.id = companyId;
	
	var status = $("input[name='mStatus']:checked").val();
	if(Utils.isNull(status)){
		showAlert("请选择账户类型!");
		return false;
	}
	data.status = status;
	// 试用账户
	if (status == CompanyStatus.TEST) {
		var validUntilDate = $("#mValidUntilDate").val();
		if (Utils.isNull(validUntilDate)) {
			showAlert("请选择有效期!");
			return false;
		}
		data.validUntilDate = validUntilDate;
		// 是否加水印
		var isWatermark = $('#mIsWatermark').is(":checked");
		data['isWatermark'] = isWatermark;
	}
	else {
		data['isWatermark'] = false;
	}
	
	// 调用接口
	var response = callInterface("post", "saas/company/modifyCompanyStatus", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		$('#modifyCompanyStatusDialog').modal("hide");
		// 刷新
		queryCompany(currPage);
	} else {
		showErrorMsg(response.code, response.message);
	}
	return false;
}

/**
 * 设置启用禁用
 */
function modifyCompanyStatus(vo) {
	// 显示对话框
	$("#modifyCompanyStatusDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#modifyCompanyStatusForm')[0].reset();
	$("#companyId").val(vo.id);
	// 状态
	var status = vo.status;
	if (status == CompanyStatus.TEST) {
		$("#mValidUntilDate").val(vo.validUntilDate);
		$("#mIsWatermark").prop("checked", vo.isWatermark);
		$(".mValidUntilDateTd").show();
	}
	else {
		$("#mValidUntilDate").val("");
		$("#mIsWatermark").prop("checked", false);
		$(".mValidUntilDateTd").hide();
	}
	$("#mStatus" + status).prop('checked', true);
	updateLayuiForm();
}

function toThirdLogin(companyId){
	// 调用接口
	var response = callInterface("post", "saas/company/getCompanyMainAccount", {"id":companyId }, false);
	if (response.code == 0) {
	    if(Utils.isNotNull(response.data)){
	    	var username = response.data.username;
	    	var password = response.data.password;
	    	var domainName = response.data.domainName;
	    	if(Utils.isNotNull(username) && Utils.isNotNull(password)){
				var param = "third_login?username=" + encodeURI(username) + "&password=" + password;
				window.open(encodeURI(domainName + param), "_blank"); 
			}
	    }else{
	    	showAlert('账户信息有误，请联系管理员!');
			return false;
	    }    
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 充值弹框
 * @param companyId
 * @param companyName
 */
function showRechargeCompanyDialog(companyId, companyName){
	// 显示对话框
	$("#rechargeCompanyDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});

	// 重置表单
	$('#RechargeCompanyForm')[0].reset();
	$("#RechargeCompanyId").val(companyId);
	$("#RechargeCompanyName").html(companyName);
	$("#cTradeType").val("");
	updateLayuiForm();
}

/**
 * 充值
 * @returns {Boolean}
 */
function confirmRechargeCompany(){
	// 获取参数
	var data = {};
	data['companyId'] = $.trim($('#RechargeCompanyId').val());
	var tradeType = $.trim($("#cTradeType option:selected").val());
	if (Utils.isNull(tradeType)) {
		showAlert("请选择充值类型!");
		return false;
	}
	data['tradeType'] = tradeType;
	var amount = $.trim($('#cAmount').val());
	if (amount == "") {
		showAlert("充值金额不能为空!");
		return false;
	}
	data['amount'] = amount;
	var payment = $.trim($('#cPayment').val());
	if (payment == "") {
		showAlert("实付金额不能为空!");
		return false;
	}
	data['payment'] = payment;
	data['remark'] = $.trim($('#cRemark').val());;

	// 调用接口
	var response = callInterface("post", "saas/company/rechargeCompany", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');

		// 关闭对话框
		$('#rechargeCompanyDialog').modal("hide");

		// 刷新
		queryCompany(currPage);
	} else {
		showErrorMsg(response.code, response.message);
	}
}

function showResetPasswordDialog(userId, userName){
	// 显示对话框
	$("#resetPasswordDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});

	// 重置表单
	$('#resetPasswordForm')[0].reset();
	$("#rUserId").val(userId);
	$("#rUserName").html(userName);
}

/**
 * 重置密码
 */
function resetPassword() {
	// 获取数据
	var resetPassword = $.trim($('#resetPassword').val());
	if (Utils.isNull(resetPassword)) {
		showAlert('新密码不能为空!');
		return false;
	}
	
	var resetChkpwd = $.trim($('#resetChkpwd').val());
	if (Utils.isNull(resetChkpwd)) {
		showAlert('确认新密码不能为空!');
		return;
	}
	
	if (resetPassword != resetChkpwd) {
		showAlert('两次输入密码不一致!');
		return;
	}
	
	// 设置参数
	var $data = {
		"id" : $.trim($("#rUserId").val()),
		"newPassword" : $.md5(resetPassword)
	}

	// 调用接口
	var response = callInterface("post", "saas/company/resetUserPassword", $data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		$('#resetPasswordDialog').modal("hide");
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 显示修改对话框
 */
function showPlayConfigDialog($id) {
	// 显示对话框
	$("#setPlayConfigDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#setPlayConfigForm')[0].reset();
	
	// 是否播放竞价广告:否
	$("#mId").val($id);
	
	// 获取详情
	initPlayConfig($id);
}

/**
 * 初始化设备配置
 */
function initPlayConfig(companyId){
	// 调用接口
	var response = callInterface("post", "saas/playManagement/getPlayerGlobalOption", {
		'companyId' : companyId
	}, false);
	if (response.code == 0) {
		var data = response.data;
		$("#taskPeriod").val(data.taskPeriod);
		//$("#heartPeriod").val(data.heartPeriod);
		$("#reporPeriod").val(data.reporPeriod);
		$("#timeZone").val(data.timeZone);
		
		// 是否播放竞价广告
		if(Utils.isNotNull(data.isGetDsp)){
			$("input[name=isGetDsp]").prop('checked',false);
			if(data.isGetDsp){
				$("#isGetDsp_1").prop('checked',true);
			}else{
				$("#isGetDsp_0").prop('checked',true);
			}
		}
		// 是否支持直播上屏
		if(Utils.isNotNull(data.isLive)){
			$("input[name=isLive]").prop('checked',false);
			if(data.isLive){
				$("#isLive_1").prop('checked',true);
			}else{
				$("#isLive_0").prop('checked',true);
			}
		}
		/*if (Utils.isNotNull(data.serverAddress)) {
			$("#serverAddress").val(data.serverAddress);
		}*/
		updateLayuiForm();
	}
}

/**
 * 保存系统全局配置
 */
function setPlayerGlobalOption(){
	
	var data = {};
	
	var companyId = $("#mId").val();
	data['companyId'] = companyId;
	
	var taskPeriod = $('#taskPeriod').val();
	if( Utils.isNotNull(taskPeriod) ){
		if(isNaN(taskPeriod) ){
			showAlert('获取任务周期必须是数字类型!');
			return false;
		}
	}else{
		showAlert('获取任务周期不能为空!');
		return false;
	}
	data['taskPeriod'] = taskPeriod;
	
	/*var heartPeriod = $('#heartPeriod').val();
	if( Utils.isNotNull(heartPeriod) ){
		if( isNaN(heartPeriod) ){
			showAlert('发送心跳周期必须是数字类型!');
			return false;
		}
	}else{
		showAlert('发送心跳周期不能为空!');
		return false;
	}
	data['heartPeriod'] = heartPeriod;*/
	
	var reporPeriod = $('#reporPeriod').val();
	if( Utils.isNotNull(reporPeriod) ){
		if( isNaN(reporPeriod) ){
			showAlert('系统参数上报周期必须是数字类型!');
			return false;
		}
	}else{
		showAlert('系统参数上报周期不能为空!');
		return false;
	}
	data['reporPeriod'] = reporPeriod;
	
	var isGetDsp = $("input[name=isGetDsp]:checked").val();
	data['isGetDsp'] = isGetDsp;
	
	var isLive = $("input[name=isLive]:checked").val();
	data['isLive'] = isLive;
	
	var timeZone = $('#timeZone').val();	
	if(Utils.isNull(timeZone)){
		showAlert('设备所在时区不能为空!');
		return false;
	}
	data['timeZone'] = timeZone;
	
	//var serverAddress = $('#serverAddress').val();
	//data['serverAddress'] = serverAddress;
	
	// 调用接口
	var response = callInterface("post", "saas/playManagement/setPlayerGlobalOption", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		$('#setPlayConfigDialog').modal("hide");
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 查看充值记录
 * 
 * @param companyId
 */
function toViewTradeRecord(companyId, companyName){
	$("#tradeRecordCompanyName").html(companyName);
	queryTradeRecord(companyId, null, null);
}

/**
 * 查询充值记录
 * 
 * @param pageIndex
 * @param pageSize
 * @returns {Boolean}
 */
function queryTradeRecord(companyId, pageIndex, pageSize) {

    // 显示对话框
    $("#tradeRecordDialog").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });

    // 组装参数
    var data = {};
    data.companyId = companyId;
    // 设置分页参数
    setPageIndex(data, pageIndex, pageSize);

    // 调用接口
    var response = callInterface("post", "saas/company/queryTradeRecord",
        data, false);
    if (response.code == 0) {

        // 清空表格及分页
        $("#tradeRecordTable tr:not(:first)").remove();
        $("#tradeRecord_pageDiv").html("");

        var count = response.data.totalCount;
        if (count == null || count == 0) {
            var cols = $("#tradeRecordTable").find("tr:first th");
            $('#tradeRecordTable').append("<tr><td colspan='" + cols.length + "'>无数据!</td></tr>");
            return false;
        }

        var list = response.data.recordList;
        if (list != null && list.length > 0) {
            for (var i in list) {
                var trHtml = "<tr>";
                trHtml += "<td align='center'>" + (Number(i) + 1) + "</td>";
                trHtml += "<td align='center'>" + list[i].createdTime + "</td>";
                trHtml += "<td align='center'>" + list[i].tradeTypeName + "</td>";
                trHtml += "<td align='center'>" + Utils.toFormatDecimal(list[i].amount, 2) + "</td>";
                trHtml += "<td align='center'>" + Utils.toFormatDecimal(list[i].payment, 2) + "</td>";
                trHtml += "<td align='center'>" + Utils.toFormatDecimal(list[i].balance, 2) + "</td>";
                trHtml += "<td align='center'>" + list[i].operatorName + "</td>";
                trHtml += "</tr>";
                // 动态添加一行
                $('#tradeRecordTable').append(trHtml);
            }
        }

        // 调用分页
        layui.use(['laypage'], function() {
            var laypage = layui.laypage;
            laypage.render({
                elem: 'tradeRecord_pageDiv',
                // pages : pages,
                curr: pageIndex || 1, // 当前页
                count: count,
                limit: pageSize,
                skip: true, // 是否开启跳页
                layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                groups: 5, // 连续显示分页数
                jump: function(obj, first) { // 触发分页后的回调
                    // 一定要加此判断，否则初始时会无限刷新
                    if (!first) {
                        // 点击跳页触发函数自身，并传递当前页：obj.curr
                        queryTradeRecord(companyId, obj.curr, obj.limit);
                    }
                }
            });
        });
    }
}